const execSQL = require("../../db/mysql");
const { createOrderID } = require("../../utils/order");
var moment = require("moment");
async function addOrderDetail(products, orderID) {
    try {
        for (let i in products) {
            let sql =
                "insert into orderdetails(orderID,productID,productNum,unitPrice,total_productPrice,orderState) values(?,?,?,?,?,?)";
            let sqlParams = [
                orderID,
                products[i].productID,
                products[i].num,
                products[i].unitPrice,
                products[i].total_product_price,
                products[i].orderState,
            ];
            let result = await execSQL(sql, sqlParams);
        }
    } catch (error) {}
}
async function addOrder(body) {
    try {
        let orderID = createOrderID();
        let sql =
            "insert into orders(orderID,userID,businessID,orderPrice,payPrice,orderTime,remark,addressID) values(?,?,?,?,?,?,?,?)";
        let sqlParams = [
            orderID,
            body.userID,
            body.businessID,
            body.orderPrice,
            body.payPrice,
            moment().format("yyyy-MM-DD HH:mm:ss"),
            body.remark,
            body.addressID,
        ];

        let result = await execSQL(sql, sqlParams);
        //
        /* 添加订单后添加订单明细 */
        const products = body.products;
        const result2 = await addOrderDetail(products, result.insertId);
        return {
            code: 1,
            message: "添加成功!",
            data: {
                orderID: orderID,
            },
        };
    } catch (error) {
        return {
            code: 1,
            message: "添加失败!",
            data: "",
        };
    }
}
async function getAllOrder(userID) {
    try {
        let sql = `select 
        orders.id as id ,
        orders.orderID as orderID,
        orders.userID as userID,
        orderdetails.productID as productID,
        product.productName as productName,
        picture.url as productPicture,
        orderdetails.productNum as productNum,
        orderdetails.total_productPrice,
        orderdetails.orderState,
        orders.orderPrice as orderPrice,
        orders.payPrice as payPrice,
        orders.ordertime as orderTime

        from 
        orders,orderdetails,picture,product
        where 
        orders.ID=orderdetails.orderID and userID=?  and product.ID=orderdetails.productID and picture.productID=orderdetails.productID
        and picture.desc='商品展示'
        GROUP BY 
        orders.id,orderdetails.productID
        ORDER BY id desc`.replaceAll("\n", " ");

        let sqlParams = [userID];
        let result = await execSQL(sql, sqlParams);

        for (let i in result) {
            result[i].orderTime = moment(result[i].orderTime)
                .utcOffset(8)
                .format("YYYY-MM-DD HH:mm:ss");
        }

        result = handleResult(result);

        return {
            code: 1,
            message: "查询全部订单成功",
            data: result,
        };
    } catch (error) {
        return {
            code: 1,
            message: "查询全部订单失败",
        };
    }
}
async function getDetail(query) {
    try {
        let sql = `SELECT 
        orderdetails.id as id,
        orders.orderID,
        orderdetails.orderState,
        orderdetails.productID,
        product.productName,
        picture.url,
        orderdetails.unitPrice,
        orderdetails.productNum,
        orderdetails.total_productPrice,
        address.id as addressID,
        address.consignee,
        address.tel,
        address.address
        FROM orders,orderdetails,address,picture,product
        where
        orders.orderID=? and
        orders.ID=orderdetails.orderID and
        orders.userID=? and
        orderdetails.productID=? and
        address.id=orders.addressID and
        picture.productID=orderdetails.productID and
        picture.desc='商品展示' and 
        product.id=orderdetails.productID`;
        let sqlParams = [query.orderID, query.userID, query.productID];
        let result = await execSQL(sql, sqlParams);
        return {
            code: 1,
            message: "查询订单详情成功",
            data: result,
        };
    } catch (error) {
        return {
            code: 0,
            message: "查询订单详情失败",
        };
    }
}
async function cancelOrder(id) {
    try {
        let sql = "update orderdetails set orderState = -1 where id=?";
        let sqlParams = [id];
        let result = await execSQL(sql, sqlParams);
        return {
            code: 1,
            message: "取消订单成功",
        };
    } catch (error) {
        return {
            code: 0,
            message: "取消订单失败",
        };
    }
}
function handleResult(resData) {
    let tempArr = [];
    let Data = [];
    for (let i = 0; i < resData.length; i++) {
        if (tempArr.indexOf(resData[i].orderID) === -1) {
            Data.push({
                orderID: resData[i].orderID,
                products: [resData[i]],
            });
            tempArr.push(resData[i].orderID);
        } else {
            for (let j = 0; j < Data.length; j++) {
                if (Data[j].orderID == resData[i].orderID) {
                    Data[j].products.push(resData[i]);
                    break;
                }
            }
        }
    }
    for (let i in Data) {
        Data[i] = Data[i].products;
    }
    return Data;
}
module.exports = {
    addOrder,
    getAllOrder,
    getDetail,
    cancelOrder
};
